# -*-coding:utf-8 -*-
# author: leemon
# datetime: 2020/9/10 16:43
from bs4 import BeautifulSoup
import requests

eureka_url = 'http://192.168.20.18:8080/eureka/apps/'


class Eureka:
    def __init__(self, url):
        self.url = url

    def get_registry_apps(self):
        res = requests.get(self.url)
        soup = BeautifulSoup(res.text, 'html.parser')
        instances = soup.find_all('instance')
        apps = []
        for instance in instances:
            # instanceid, hostname, app, ipaddr, status, port
            tmp = {'name': instance.app.get_text(), 'instanceid': instance.instanceid.get_text(),
                   'hostname': instance.hostname.get_text(), 'ipaddr': instance.ipaddr.get_text(),
                   'port': instance.port.get_text(), 'status': instance.status.get_text(),
                   'socket': '{}:{}'.format(instance.ipaddr.get_text(), instance.port.get_text()),
                   }
            apps.append(tmp)
        return apps

    def get_app(self, ipaddr, port):
        apps = self.get_registry_apps()
        for app in apps:
            if app['ipaddr'] == ipaddr and app['port'] == port:
                return app

        return False

    def change_app_status(self, app_dict, status):
        '''
        修改eureka中注册app的状态
        :param app:
        :param status: 0. UP 1 OUT_OF_SERVICE 2 SHUTDOWN
        :return:
        '''
        status_list = ['UP', 'OUT_OF_SERVICE', 'SHUTDOWN']
        app = app_dict['name']
        instanceid = app_dict['instanceid']
        request_url = '%s%s/%s/status?value=%s' % (self.url, app, instanceid, status_list[status])
        res = requests.put(request_url)
        if res.status_code != 200:
            return False
        return True


if __name__ == '__main__':
    eureka_client = Eureka(eureka_url)
    print(len(eureka_client.get_registry_apps()))
    # for i in eureka_client.get_registry_apps():
    #     print(i)

    app = eureka_client.get_app('172.16.245.40', '5000')
    print(app)
